//
// Copyright 2011 ReedRex Corp
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// BookService.m
// Cloud BookShelf
//
// Created by Shunichi Takagi on 11/02/25.
//

#import "BookService.h"


@implementation BookService

@synthesize tableContext;
@synthesize enabledBatch;
@synthesize blobContext;


- (id) initWithClient:(StorageClient *)aClient enabledBatch:(bool) aEnabledBatch {
	self.tableContext = [aClient createTableContext];
	self.enabledBatch = aEnabledBatch;
	
	self.blobContext = [aClient createBlobContext];
	
	return self;
}

- (void) dealloc {
	[self.tableContext release];
	self.tableContext = nil;
	
	[super dealloc];
}

- (void) commit {
	@try {
		if( self.enabledBatch ) {
			[self.tableContext setSaveChangesOptions:Batch];
		}
		
		[self.tableContext saveChanges];
	}
	@catch (NSException * e) {
		NSLog(@"Exception Occured. %@", e);
	}
}

- (Book *) insert:(Book *)aBook {
	NSLog(@"Insert");
	[aBook setPartitionKey:[[UIDevice currentDevice] uniqueIdentifier]]; //PartitionKeyとしてiPhoneのUDIDを使う
	[aBook setRowKey:[ODataGUID GetNewGuid]]; //RowKeyはGUIDにしておく
	
	[self.tableContext addObject:@BOOK_ENTITY_NAME object:aBook];
	
	if ( !self.enabledBatch ){
		//バッチモードでない場合だけSaveChangesする
		[self commit];
	}
	
	return aBook;
}

- (Book *) update:(Book *)aBook {
	[self.tableContext updateObject:aBook];
	
	if ( !self.enabledBatch ){
		//バッチモードでない場合だけSaveChangesする
		[self commit];
	}
	
	return aBook;
}

- (void) remove:(Book *)aBook {
	[self.tableContext deleteObject:aBook];
	if ( !self.enabledBatch ){
		[self commit];
	}
}

- (NSArray *) find:(NSString *)aQuery {
	NSString *deviceId = [[UIDevice currentDevice] uniqueIdentifier];
	
	//デフォルトでPartitionKeyによる絞り込みを入れておく
	NSString *q = [NSString stringWithFormat:@"PartitionKey eq '%@'%@%@", deviceId, ( aQuery != @"" ? @" and " : @"" ), aQuery];
	
	DataServiceQuery *query = [[DataServiceQuery alloc] initWithUri:@BOOK_ENTITY_NAME objectContext:self.tableContext];
	[query filter:q];
	
	QueryOperationResponse *response = [query execute];
	NSArray *result = [response getResult];
	
	NSLog(@"Query Result");
	for(Book *r in result){
		NSLog(@"Book(title=%@, author=%@, rate=%@) PK:%@ RK:%@ Timestamp:%@", r.title, r.author, r.rate, r.PartitionKey, r.RowKey, r.Timestamp);
	}
	
	return result;
}

- (NSArray *) findByQueries:(Queries *)aQueries {
	return [self find:aQueries.filterString];
}

- (UIImage *) fetchImage:(Book *)aBook {
	NSData *data = [blobContext fetch:[NSString stringWithFormat:@"%@.png", aBook.RowKey] withContainer:@"container"];
	UIImage* image = [[[UIImage alloc] initWithData:data] autorelease];
	
	return image;
}

- (void) storeImage:(UIImage *)aImage with:(Book *)aBook {
	NSData* data = [[[NSData alloc] initWithData:UIImagePNGRepresentation( aImage )] autorelease];
	[blobContext store:data to:[NSString stringWithFormat:@"%@.png", aBook.RowKey] withContainer:@"container"];
	
	return;
}

@end
